package cn.xanderye.ribbon.consumer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

@Service
public class HelloService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
    public String helloService() {
        long start = System.currentTimeMillis();
        String string = restTemplate.getForObject("http://HELLO-SERVICE/hello", String.class);
        logger.info("SpendTime:" + (System.currentTimeMillis() - start));
        return string;
    }

    @HystrixCommand
    public Future<String> helloServiceSync() {
        // 异步执行
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                return restTemplate.getForObject("http://HELLO-SERVICE/hello", String.class);
            }
        };
    }


    public String helloFallback() {
        return "error";
    }
}
